package com.yj_app.qualitytest.base;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.yj_app.qualitytest.R;
import com.yj_app.qualitytest.callback.DialogCallback;
import com.yj_app.qualitytest.callback.UpRes;
import com.yj_app.qualitytest.common.Config;
import com.yj_app.qualitytest.common.NetConfig;
import com.yj_app.qualitytest.info.BcInfo;
import com.yj_app.qualitytest.info.CompanyInfo;
import com.yj_app.qualitytest.info.HdInfo;
import com.yj_app.qualitytest.info.Loginfo;
import com.yj_app.qualitytest.info.SubScoreInfo;
import com.yj_app.qualitytest.info.up.MsgBean;
import com.yj_app.qualitytest.info.up.QualityVO;
import com.yj_app.qualitytest.util.DateUtils;
import com.yj_app.qualitytest.util.GsonUtil;
import com.yj_app.qualitytest.util.PreferencesManager;
import com.yj_app.qualitytest.util.ToastUtils;

import org.litepal.LitePal;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;

import static com.yj_app.qualitytest.base.QtApplication.getContext;


/**
 * 文 件 名: BaseActivity
 * 创 建 人: Allen
 * 创建日期: 16/12/24 15:33
 * 邮   箱: AllenCoder@126.com
 * 修改时间：
 * 修改备注：
 */
public class BaseActivity extends AppCompatActivity {
    /**
     * 日志输出标志getSupportActionBar().
     **/

    protected final String TAG = this.getClass().getSimpleName();
    private LinearLayout rootLayout;
    public LinearLayout layoutBtn;
    Toolbar toolbar;
    public ImageView seeDetail, up_load;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //横屏
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }


        // 经测试在代码里直接声明透明状态栏更有效
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
//                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//        }
        // 这句很关键，注意是调用父类的方法
        super.setContentView(R.layout.activity_base);
        initToolbar();
    }


    public void setTitle(int titleId) {
        toolbar.setTitle(titleId);
    }

    public void setTitle(String title) {
        if (!TextUtils.isEmpty(title)) {
            toolbar.setTitle(title);
        }
        toolbar.setVisibility(View.VISIBLE);
    }

    public void setTitleWithBack(String title) {
        setTitle(title);
        if (getSupportActionBar() != null) {
            // Enable the Up button
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowTitleEnabled(true);

        }
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                leftBack();
            }
        });
    }

    public void leftBack() {
        finish();
    }

    private void initToolbar() {
        toolbar = findViewById(R.id.toolbar);
        if (toolbar != null) {
            setSupportActionBar(toolbar);
        }


    }

    public static String formatDouble(double d) {
        BigDecimal bg = new BigDecimal(d).setScale(1, RoundingMode.UP);
        double num = bg.doubleValue();
        if (Math.round(num) - num == 0) {
            return String.valueOf((long) num);
        }
        return String.valueOf(num);
    }

    public void fullscreen(boolean enable) {

        if (enable) { //显示状态栏

            WindowManager.LayoutParams lp = getWindow().getAttributes();

            lp.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;

            getWindow().setAttributes(lp);

            getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);

        } else { //隐藏状态栏

            WindowManager.LayoutParams lp = getWindow().getAttributes();

            lp.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);

            getWindow().setAttributes(lp);

            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);

        }

    }


    @Override
    public void setContentView(int layoutId) {
        setContentView(View.inflate(this, layoutId, null));
    }

    @Override
    public void setContentView(View view) {
        rootLayout = (LinearLayout) findViewById(R.id.root_layout);
        if (rootLayout == null) {
            return;
        }
        layoutBtn = findViewById(R.id.layout_btn);
        rootLayout.addView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        initToolbar();
        initRightView();
    }

    private void initRightView() {

        View view = View.inflate(this, R.layout.toolbar_btn_score, null);
        up_load = view.findViewById(R.id.up_load);
        seeDetail = view.findViewById(R.id.see_detail);
        layoutBtn.addView(view);
    }

    public void toastSuccess(String s) {
        ToastUtils.toastSuccess(s, true);
    }

    public void toastError(String s) {
        ToastUtils.toastError(s, true);
    }

    public void toastWaring(String s) {
        ToastUtils.toastWarn(s, true);
    }

    public void toastInfo(String s) {
        ToastUtils.toastInfo(s, true);
    }

    public boolean checkNull(MaterialEditText editText, String errmsg) {
        if (TextUtils.isEmpty(editText.getText().toString())) {
            toastError(errmsg);
            return false;
        } else {
            return true;
        }
    }

    public String getEdittext(MaterialEditText mUserName) {
        return mUserName.getText().toString().trim();
    }

    public void startactivity(Class mainActivityClass) {
        startActivity(mainActivityClass, null);
    }

    public void startActivity(Class mainActivityClass) {
        startActivity(mainActivityClass, null);
    }

    public void startActivity(Class mainActivityClass, Bundle bundle) {
        Intent intent = new Intent(this, mainActivityClass);
        if (bundle != null)
            intent.putExtras(bundle);
        startActivity(intent);
    }

    public void startActivity(Class mainActivityClass, Bundle bundle, int requestCode) {
        Intent intent = new Intent(this, mainActivityClass);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
    }

    public void startActivity(Class mainActivityClass, int requestCode) {
        Intent intent = new Intent(this, mainActivityClass);
        startActivityForResult(intent, requestCode);
    }


    private String data2json() {
        CompanyInfo companyInfo=PreferencesManager.getInstance(getContext()).get(Config.COMPANY_INFO, CompanyInfo.class);
        Loginfo loginfo = PreferencesManager.getInstance(this).get(Config.LOGINFO, Loginfo.class);
        MsgBean msgBean = new MsgBean();
        List<QualityVO> qualityVOList = new ArrayList<>();
        List<SubScoreInfo> subScoreInfos = LitePal.findAll(SubScoreInfo.class);
        for (SubScoreInfo subScoreInfo : subScoreInfos) {
            QualityVO qualityVO = new QualityVO();
            //主任id
            qualityVO.setPk_headcode(subScoreInfo.getZrid());
            //生产线id
            qualityVO.setPk_scxcode(subScoreInfo.getSclineid());
            //机器号
            qualityVO.setJqhcode(subScoreInfo.getMachineno());
            //车间id
            qualityVO.setPk_cjcode(subScoreInfo.getWorkspaceid());
            //用户id
            qualityVO.setPk_usercode(loginfo.getCode());
            //包装方式
            qualityVO.setBzfs(subScoreInfo.getBzfs());
            //班组
            qualityVO.setTeam(subScoreInfo.getTeamname());
            //增加时间
            qualityVO.setAddtime(subScoreInfo.getTime());
            //上传时间
            qualityVO.setTesttime(DateUtils.convertToString(System.currentTimeMillis(),DateUtils.TIME_FORMAT));

//            **外观*/
//            public final static int TTYPE_WG = 1;
//            /**粘口*/
//            public final static int TTYPE_ZK = 2;
//            /**卫生*/
//            public final static int TTYPE_VS = 3;
//            /**称重*/
//            public final static int TTYPE_CZ = 4;
//            /**厚度*/
//            public final static int TTYPE_HD = 5;

//            String[] guamiantitle = {"外观", "卫生", "厚度", "粘口", "标称"};
//            String[] zhifentitle = {"外观", "卫生", "封口", "标称"};
//            String[] wathertitle = {"外观", "卫生"};
            //大的类型
            qualityVO.setItype(TextUtils.equals("外观",subScoreInfo.getCheckxmpname())?"1":
                    TextUtils.equals("粘口",subScoreInfo.getCheckxmpname())?"2":
                            TextUtils.equals("卫生",subScoreInfo.getCheckxmpname())?"3":
                                    TextUtils.equals("标称",subScoreInfo.getCheckxmpname())?"4":"5");
            //指标主键
            qualityVO.setPk_ccode(String.valueOf(subScoreInfo.getContentId()));
            //扣分
            qualityVO.setScore(String.valueOf(subScoreInfo.getScore()));

            qualityVO.setPk_org(companyInfo.getCorp());

            qualityVO.setPk_workercode(subScoreInfo.getNicknameid());

            qualityVOList.add(qualityVO);
        }

        List<HdInfo> hdInfoList=LitePal.findAll(HdInfo.class);
        for (HdInfo hdInfo:hdInfoList){
            QualityVO qualityVO = new QualityVO();

            //主任id
            qualityVO.setPk_headcode(hdInfo.getUsercode());
            //生产线id
            qualityVO.setPk_scxcode(hdInfo.getqLineId());
            //机器号
            qualityVO.setJqhcode("");
            //车间id
            qualityVO.setPk_cjcode(hdInfo.getCjcode());
            //用户id
            qualityVO.setPk_usercode(loginfo.getCode());
            //包装方式
            qualityVO.setBzfs("");
            //班组
            qualityVO.setTeam(hdInfo.getGcode());
            //增加时间
            qualityVO.setAddtime(hdInfo.getTime());
            //上传时间
            qualityVO.setTesttime(DateUtils.convertToString(System.currentTimeMillis(),DateUtils.TIME_FORMAT));

//            **外观*/
//            public final static int TTYPE_WG = 1;
//            /**粘口*/
//            public final static int TTYPE_ZK = 2;
//            /**卫生*/
//            public final static int TTYPE_VS = 3;
//            /**称重*/
//            public final static int TTYPE_CZ = 4;
//            /**厚度*/
//            public final static int TTYPE_HD = 5;

//            String[] guamiantitle = {"外观", "卫生", "厚度", "粘口", "标称"};
//            String[] zhifentitle = {"外观", "卫生", "封口", "标称"};
//            String[] wathertitle = {"外观", "卫生"};
            //大的类型
            qualityVO.setItype("5");
            //指标主键
            qualityVO.setPk_ccode(String.valueOf(hdInfo.getqScoreInfoId()));
            //扣分
            qualityVO.setScore(String.valueOf(hdInfo.getScore()));



            qualityVO.setPk_org(companyInfo.getCorp());

            qualityVOList.add(qualityVO);


        }
        List<BcInfo> bcInfoList=LitePal.findAll(BcInfo.class);
        for (BcInfo bcInfo:bcInfoList){

            QualityVO qualityVO = new QualityVO();

            //主任id
            qualityVO.setPk_headcode(bcInfo.getUsercode());
            //生产线id
            qualityVO.setPk_scxcode(bcInfo.getqLineId());
            //机器号
            qualityVO.setJqhcode(bcInfo.getMachino());
            //车间id
            qualityVO.setPk_cjcode(bcInfo.getCjcode());
            //用户id
            qualityVO.setPk_usercode(loginfo.getCode());
            //包装方式
            qualityVO.setBzfs(bcInfo.getBzfs());
            //班组
            qualityVO.setTeam(bcInfo.getGcode());
            //增加时间
            qualityVO.setAddtime(bcInfo.getTime());
            //上传时间
            qualityVO.setTesttime(DateUtils.convertToString(System.currentTimeMillis(),DateUtils.TIME_FORMAT));

//            **外观*/
//            public final static int TTYPE_WG = 1;
//            /**粘口*/
//            public final static int TTYPE_ZK = 2;
//            /**卫生*/
//            public final static int TTYPE_VS = 3;
//            /**称重*/
//            public final static int TTYPE_CZ = 4;
//            /**厚度*/
//            public final static int TTYPE_HD = 5;

//            String[] guamiantitle = {"外观", "卫生", "厚度", "粘口", "标称"};
//            String[] zhifentitle = {"外观", "卫生", "封口", "标称"};
//            String[] wathertitle = {"外观", "卫生"};
            //大的类型
            qualityVO.setItype("4");
            //指标主键
            qualityVO.setPk_ccode(String.valueOf(bcInfo.getqScoreInfoId()));
            //扣分
            qualityVO.setInum(bcInfo.getCount());
            qualityVO.setInum2(bcInfo.getWucha());

            qualityVO.setPk_org(companyInfo.getCorp());

            qualityVOList.add(qualityVO);


        }

        msgBean.setList(qualityVOList);
        msgBean.setMethod(1);
        return getSoapstr(GsonUtil.toJson(msgBean));

    }

    public void upLoadData(UpRes upRes) {

        OkGo.<String>post(NetConfig.BASEUrl_S + NetConfig.UPDAE_SORE)//
                .tag(this).upBytes(data2json().getBytes(), MediaType.parse("text/xml;charset=UTF-8")).execute(new DialogCallback<String>(this) {
            @Override
            public void onSuccess(Response<String> response) {
                String s = response.body();
                if (TextUtils.isEmpty(s)) {
                    toastSuccess("上传失败");
                    upRes.error();
                    return;
                }
                if (s.indexOf("<return>") > 0)
                    s = s.substring(s.indexOf("<return>") + 8, s.indexOf("</return>"));
                else
                    s = s.substring(s.indexOf("ns1:return") + 11, s.indexOf("</ns1:return>"));
                MsgBean msgBean = GsonUtil.fromJson(s, MsgBean.class);
                if (msgBean.isSuccess()) {
                    toastSuccess("上传成功" + msgBean.getMsg());
                    LitePal.deleteAll(SubScoreInfo.class);
                    LitePal.deleteAll(HdInfo.class);
                    LitePal.deleteAll(BcInfo.class);
                    upRes.success();
                } else {
                    toastError(msgBean.getMsg());
                    upRes.error();
                }

            }
            @Override
            public void onError(Response<String> response) {
                super.onError(response);
            }
        });
    }


    static String getSoapstr(String jsonstr) {

        return "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:iqu=\"http://ws.jshmy.itf.nc/IQuality\">\n" +
                "   <soapenv:Header/>\n" +
                "   <soapenv:Body>\n" +
                "      <iqu:executeBill>\n" +
                "         <!--Optional:-->\n" +
                "         <iqu:string>" + cnToUnicode(jsonstr) + "</iqu:string>\n" +
                "      </iqu:executeBill>\n" +
                "   </soapenv:Body>\n" +
                "</soapenv:Envelope>";
    }

    private static String cnToUnicode(String cn) {
        char[] chars = cn.toCharArray();
        String returnStr = "";
        for (int i = 0; i < chars.length; i++) {
            returnStr += "\\u" + Integer.toString(chars[i], 16);
        }
        return returnStr;
    }
}
